package com.commerceerp.system.util;

import com.alibaba.fastjson.JSON;
import com.commerceerp.system.entity.OrderVo;
import com.commerceerp.system.entity.PorderInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/3/16.
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    //自动生成id
    public static String getUUID() {

        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 接口调用 GET
     */
    public static String httpURLConectionGET(String getUrl) {
        try {
            URL url = new URL(getUrl);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println(sb.toString());
            return sb.toString();
        } catch (Exception e) {
            System.out.println("-----------GET请求失败-----------↓");
            e.printStackTrace();
            System.out.println("-----------GET请求失败-----------↑");
            return null;
        }

    }


    /**
     * 发送HttpPost请求
     *
     * @param postUrl 服务地址
     * @param param   json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     * @return 成功:返回json字符串<br/>
     */
    public static String httpURLConnectionPOST(String postUrl, String param) {
        try {
            URL url = new URL(postUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(param);
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = null;
            StringBuffer content = new StringBuffer();
            while ((line = in.readLine()) != null) {
                // line 为返回值，这就可以判断是否成功
                content.append(line);
            }
            in.close();
            System.out.println(content.toString());
            return content.toString();
        } catch (Exception e) {
            System.out.println("-----------POST请求失败-----------↓");
            e.printStackTrace();
            System.out.println("-----------POST请求失败-----------↑");
            return null;
        }
    }

    /**
     * 发送HttpPost请求
     *
     * @param strURL 服务地址
     * @param params
     * @return 成功:返回json字符串<br/>
     */
    public static String jsonPost(String strURL, Map<String, String> params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(obj2String(params));
            out.flush();
            out.close();

            int code = connection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }

            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                return result;
            }

        } catch (IOException e) {
            System.out.println("-----------jsonPost请求失败-----------↓");
            e.printStackTrace();
            System.out.println("-----------jsonPost请求失败-----------↑");
        }
        return "error"; // 自定义错误信息
    }

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Object转json字符串
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String obj2String(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            System.out.println("Parse object to String error");
            e.printStackTrace();
            return null;
        }
    }

    //获取本机ip
    public static String getIp(){
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return addr.getHostAddress().toString();
    }

    //生成订单流水号
    public static void getOrderSerialNumber(OrderVo orderInfo){
        if(StringUtils.isNotEmpty(orderInfo.getOrderDownTime())){
            String serialNumber = orderInfo.getOrderDownTime().substring(0,19);
            serialNumber = serialNumber + (int)((Math.random()*9+1)*1000);
            serialNumber = serialNumber.replace("-","").replace(":","");
            orderInfo.setSerialNumber(serialNumber);
        }
    }

    //生成采购单流水号
    public static void getPorderSerialNumber(PorderInfo orderInfo){
        if(StringUtils.isNotEmpty(orderInfo.getPorderCreateTime())){
            String serialNumber = orderInfo.getPorderCreateTime().substring(0,19);
            serialNumber = serialNumber + (int)((Math.random()*9+1)*1000);
            serialNumber = serialNumber.replace("-","").replace(":","").replace(" ","");
            orderInfo.setSerialNumber("out"+serialNumber);
        }
    }

    public static void main(String[] args) {

    }
}
